﻿using System;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO.IsolatedStorage;
using System.Collections.Generic;
using VXCompany.SilverlightLogging.ServiceProxy;
using System.Runtime.Serialization;
using System.IO;
using System.Collections.ObjectModel;

namespace VXCompany.SilverlightLogging.MVVM.Models.Stores
{
	/// <summary>
	/// Stores ExceptionMessage items in IsolatedStorageFileStream.
	/// </summary>
	public class IsoStreamStore : Store
	{
		private const string PATH = "sfgiuhseoihsef.bin";
		private DataContractSerializer serializer;
		private IsolatedStorageFile file;

		/// <summary>
		/// Creates new instance. Initializes store.
		/// </summary>
		public IsoStreamStore()
		{
			Initialize();
		}

		/// <summary>
		/// Prepares store for use.
		/// </summary>
		protected override void InitializeImpl()
		{
			try
			{
				serializer = new DataContractSerializer(typeof(ObservableCollection<ExceptionMessage>));
				file = IsolatedStorageFile.GetUserStoreForApplication();
				IsStorageAvailable = true;
			}
			catch (IsolatedStorageException)
			{
				IsStorageAvailable = false;
			}
		}

		/// <summary>
		/// Returns all ExceptionMessage items from the store.
		/// </summary>
		/// <returns></returns>
		protected override IEnumerable<ExceptionMessage> GetItemsFromStore()
		{
			try
			{
				if (file.FileExists(PATH))
				{
					using (IsolatedStorageFileStream fs = new IsolatedStorageFileStream(PATH, System.IO.FileMode.Open, file))
					{
						return DeserializeList(fs);
					}
				}
			}
			catch (IsolatedStorageException)
			{
				IsStorageAvailable = false;
			}

			return null;
		}

		/// <summary>
		/// Saves changes.
		/// </summary>
		protected override void SaveImpl()
		{
			try
			{
				using (IsolatedStorageFileStream fs = new IsolatedStorageFileStream(PATH, System.IO.FileMode.Create, file))
				{
					SerializeList(fs, InnerList);
				}
			}
			catch (IsolatedStorageException)
			{
				IsStorageAvailable = false;
			}
		}

		/// <summary>
		/// Deserializes stream to list of ExceptionMessage.
		/// </summary>
		/// <param name="stream"></param>
		/// <returns></returns>
		private ObservableCollection<ExceptionMessage> DeserializeList(Stream stream)
		{
			return serializer.ReadObject(stream) as ObservableCollection<ExceptionMessage>;
		}

		/// <summary>
		/// Serializes list of ExceptionMessage to Stream.
		/// </summary>
		/// <param name="stream"></param>
		/// <param name="list"></param>
		private void SerializeList(Stream stream, ObservableCollection<ExceptionMessage> list)
		{
			serializer.WriteObject(stream, list);
		}	
	}
}
